package com.cgsd.heyu.ui.task;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.cgsd.heyu.R;
import com.cgsd.heyu.api.ApiService;
import com.cgsd.heyu.common.Constants;
import com.cgsd.heyu.entity.EventMessage;
import com.cgsd.heyu.http.BaseResponse;
import com.cgsd.heyu.http.BaseRxSubscribe;
import com.cgsd.heyu.http.ErrorMessage;
import com.cgsd.heyu.http.RetrofitServiceManagerPhp;
import com.cgsd.heyu.http.RxjavaHelper;
import com.cgsd.heyu.ui.home.fragment.WrapperSendFragment;
import com.cgsd.heyu.ui.task.vo.EditThreeVo;
import com.cgsd.heyu.utils.DoubleUtil;
import com.cgsd.heyu.utils.RequestParams;

import org.greenrobot.eventbus.EventBus;

import okhttp3.RequestBody;

/**
 * Author: sky on 2021/3/3 15:56
 * Email: xcode126@126.com
 * Desc: 新建任务-赏金信息
 */
public class StepThreeFragment extends WrapperSendFragment implements View.OnClickListener {
    private EditText etMoney;
    private TextView tvFontAmount;//前台赏金数
    private EditText etCount;
    private TextView tvTotalAmount;//赏金总额
    private TextView tvTotalPay;//合计支付

    private double totalAmount;//总金额
    private double amount;//单价
    private int num;//任务数量

    private Handler handler = new Handler();
    private Runnable delayRunnable = new Runnable() {
        @Override
        public void run() {
            refreshAmount();
        }
    };

    public static StepThreeFragment newInstance() {
        return new StepThreeFragment();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_three_step;
    }

    @Override
    protected void initView() {
        BindViews();
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (delayRunnable != null) {
                    handler.removeCallbacks(delayRunnable);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                handler.postDelayed(delayRunnable, 500);
            }
        });
        etCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (delayRunnable != null) {
                    handler.removeCallbacks(delayRunnable);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                handler.postDelayed(delayRunnable, 500);
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onDestroyView() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        delayRunnable = null;
        super.onDestroyView();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_last:
                skipLastStep();
                break;
            case R.id.tv_save:
                goSaveThree(false);
                break;
            case R.id.tv_publish:
                goSaveThree(true);
                break;
        }
    }

    /**
     * 去保存第三步
     *
     * @param isNowPay
     */
    private void goSaveThree(boolean isNowPay) {
        if (amount == 0) {
            showToast("请输入赏金金额");
            return;
        }
        if (num == 0) {
            showToast("请输入任务数量");
            return;
        }
        if (totalAmount < 1) {
            showToast("支付总金额不能小于1");
            return;
        }
        int tid = getTid();
        if (tid == -1) {
            showToast(getString(R.string.a_config_error_tip));
            return;
        }
        if (isNowPay) {
            saveStepThreeGoPay(tid, amount, num, totalAmount);
        } else {
            saveStepThree(tid, amount, num, totalAmount);
        }
    }

    /**
     * 跳到上一步
     */
    private void skipLastStep() {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            activity.setCurrentPage(1);
        }
    }

    /**
     * bind views
     */
    private void BindViews() {
        findViewById(R.id.tv_last).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        findViewById(R.id.tv_publish).setOnClickListener(this);
        etMoney = (EditText) findViewById(R.id.et_money);
        etCount = (EditText) findViewById(R.id.et_count);
        tvTotalAmount = (TextView) findViewById(R.id.tv_total_amount);
//        tvFontTotalAmount = (TextView) findViewById(R.id.tv_font_total_amount);
        tvTotalPay = (TextView) findViewById(R.id.tv_total_pay);
        tvFontAmount = (TextView) findViewById(R.id.tv_font_amount);
    }

    /**
     * refresh amount
     */
    private void refreshAmount() {
        String moneyStr = etMoney.getText().toString().trim();
        amount = TextUtils.isEmpty(moneyStr) ? 0 : Double.parseDouble(moneyStr);//单价
        String countStr = etCount.getText().toString().trim();
        num = TextUtils.isEmpty(countStr) ? 0 : Integer.parseInt(countStr);//数量

        totalAmount = DoubleUtil.mul(amount, num, 2);//总金额
        double serviceAmount = DoubleUtil.mul(amount, 0.3, 2);//平台服务费
        double fontAmount = DoubleUtil.sub(amount, serviceAmount);//前台单价赏金数

        tvTotalAmount.setText(String.format("%1$.2f", totalAmount));
        tvTotalPay.setText(String.format("%1$.2f", totalAmount));
        tvFontAmount.setText(String.format("%1$s%2$.2f", "前台赏金数：", fontAmount));
    }

    /**
     * 获取任务id
     *
     * @return
     */
    private int getTid() {
        if (getActivity() instanceof PublishTaskActivity) {
            PublishTaskActivity activity = (PublishTaskActivity) getActivity();
            return activity.getTid();
        }
        return -1;
    }

    /**
     * 保存第三步数据,并去支付
     *
     * @param tid
     * @param price
     * @param num
     * @param totalamount
     */
    private void saveStepThreeGoPay(int tid, double price, int num, double totalamount) {
        showSubmitDialog();
        RequestBody requestBody = new RequestParams()
                .put("tid", tid)
                .put("price", price)
                .put("num", num)
                .put("totalamount", totalamount)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .saveStepThreeGoPay(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        dismissCommonSubmitDialog();
                        showToast(baseResponse.getResultMsg());
                        if (baseResponse.getCode() == Constants.SUCCESS_CODE) {
                            if (!TextUtils.isEmpty(baseResponse.getBizBody())) {//支付参数不为null去支付
                                startActivity(PayActivity.getIntent(mContext, baseResponse.getBizBody(), totalAmount));
                            }
                            EventBus.getDefault().post(new EventMessage<>(Constants.EventCode.MY_PUBLISH_REFRESH));//通知发布列表刷新
                            getActivity().finish();//关闭当前发布界面
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                        dismissCommonSubmitDialog();
                    }
                });
    }

    /**
     * 保存第三步数据
     *
     * @param tid
     * @param price
     * @param num
     * @param totalamount
     */
    private void saveStepThree(int tid, double price, int num, double totalamount) {
        showSubmitDialog();
        RequestBody requestBody = new RequestParams()
                .put("tid", tid)
                .put("price", price)
                .put("num", num)
                .put("totalamount", totalamount)
                .get();
        RetrofitServiceManagerPhp.getInstance().creat(ApiService.class)
                .saveStepThree(requestBody)
                .compose(RxjavaHelper.observeOnMainThread())
                .subscribe(new BaseRxSubscribe<BaseResponse<String>>() {
                    @Override
                    public void onSuccess(BaseResponse<String> baseResponse) {
                        dismissCommonSubmitDialog();
                        showToast(baseResponse.getResultMsg());
                        if (baseResponse.getCode() == Constants.SUCCESS_CODE) {
                            EventBus.getDefault().post(new EventMessage<>(Constants.EventCode.MY_PUBLISH_REFRESH));
                            getActivity().finish();
                        }
                    }

                    @Override
                    public void onError(ErrorMessage error) {
                        handleErrorAction(error);
                        dismissCommonSubmitDialog();
                    }
                });
    }

    @Override
    public void onRefresh(Object t) {
        if (t != null && t instanceof EditThreeVo) {
            EditThreeVo editThreeVo = (EditThreeVo) t;
            if (editThreeVo != null && editThreeVo.info != null) {
                etMoney.setText(editThreeVo.info.price + "");
                etCount.setText(editThreeVo.info.num + "");
                refreshAmount();
                etCount.setEnabled(editThreeVo.state != 4);
                etMoney.setEnabled(editThreeVo.state != 4);
            }
        }
    }
}
